import { PageContainer } from '@ant-design/pro-layout';
import React, {useRef, useState} from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import {getVolumeStatistics,invoicingFormExport,invoicingFormExports} from '../../pages/StockIO/service';
import ProTable, { ActionType } from '@ant-design/pro-table';
import request from '@/utils/request';
import { Button, Drawer, message, Spin, Upload } from 'antd';
import { exportFile, manufacturerOption } from '@/utils/utils';

export type PutOutProps = {
  admin:boolean;
  sale:boolean;
  hospital:number;
};

const HadTicket: React.FC<PutOutProps> = (props)=>{
  const actionRef = useRef<ActionType>();
  const [ticketAttList,setTicketAttList]= useState([]);
  const [showDetail, setShowDetail] = useState(false);
  const [spinningFlag,setSpinningFlag]  = useState(false);

  const handlePreview = async (file:any) => {
    window.open(file.url);
   };

   const notOpen = (record:any) =>{
     if(record.reason_type==='4'){
      return `不开票，其他原因：${record.reason}`
     }else  if(record.reason_type==='3'){
      return '不开票，两票制原因'
     }else  if(record.reason_type==='2'){
      return '不开票，尚未开票(后期会开出发票)'
     }else  if(record.reason_type==='1'){
      return '不开票，区域收费原因(一直不能开票)'
     }
     return 
   }

  //表头信息以及表值设置
  const columns: ProColumns[] = [
    {
      title:'客户代码',
      dataIndex: 'loginName',
      width:100,
      ellipsis:true,
      fixed:'left',
      // hideInTable:props.admin?false:true,
      hideInSearch:props.admin?false:true,
    },
    {
      title:'客户名称',
      dataIndex: 'cnName',
      width:200,
      fixed:'left',
      ellipsis:true,
      // hideInTable:props.admin?false:true,
      hideInSearch:props.admin?false:true,
    },
    {
      title:'客户等级',
      dataIndex: 'level',
      width:100,
      hideInSearch:props.admin?false:true,
      hideInTable:props.admin?false:true,
      valueType:'select',
      valueEnum:{
          一级:{ text: '一级' },
          二级:{ text: '二级' },
      }
    },
    {
      title:'是否开票',
      dataIndex: 'isBill',
      width: 100,
      valueType:'select',
      // hideInTable:props.hospital===1?true:false,
      valueEnum:{
        '1': { text: '是' },
        '0': { text: '否' },
      }
    },
    {
      title:'报量方式',
      dataIndex:'volumeType',
      valueType:'select',
      width:80,
      valueEnum:{
          '1' : {text:'授权'},
          '2' : {text:'非授权'},
          }
    },
    {
      title:'是否冲销',
      dataIndex:'isUpdate',
      valueType:'select',
      width:80,
      hideInSearch:props.admin&&!props.sale?false:true,
      hideInTable:props.admin&&!props.sale?false:true,
      valueEnum:{
          '0' : {text:'否'},
          '1' : {text:'是'},
          }
    },
    {
      title:'发票号码',
      width:100,
      dataIndex: 'bill_number',
      fixed:'left',
    },
    {
      title:'开票日期',
      dataIndex: 'bill_date',
      width:120,
      hideInSearch:true,
      fixed:'left',
    },
    {
      title:'开票日期',
      dataIndex: 'date',
      width:120,
      valueType:'dateRange',
      hideInTable:true,
      fixed:'left',
    },
    {
      title:'提交日期',
      dataIndex: 'create_dates',
      hideInSearch:true,
      width:100,
    },
    {
      title:'更新日期',
      dataIndex: 'update_date',
      hideInSearch:true,
      width:100,
    },
    {
      title:props.hospital===1?'购方编码-医院':'购方编码',
      dataIndex: 'bh',
      width:120,
    },
    {
      title:props.hospital===1?'购方名称-医院':'购方名称',
      dataIndex: 'purchaser',
      ellipsis:true,
      width:200,
    },
    {
      title:'票面购买方',
      width:150,
      dataIndex: 'billPurchaseName',
      hideInSearch:true,
      ellipsis:true,
      valueEnum:{
        '0' : {text:'否'},
        '1' : {text:'是'},
      }
    },
    {
      title:'托管公司',
      width:80,
      dataIndex: 'isTrusteeship',
      hideInSearch:true,
      valueEnum:{
        '0' : {text:'否'},
        '1' : {text:'是'},
      }
    },
    {
      title:'库存',
      width:60,
      dataIndex: 'isInventory',
      hideInSearch:true,
      valueEnum:{
        '0' : {text:'否'},
        '1' : {text:'是'},
      }
    },
    {
      title:'医院等级',
      dataIndex: 'hospitalGrade',
      width:100,
      hideInTable:props.hospital===1?false:true,
      hideInSearch:true,
      renderText:(_,record)=>{
        if(record.hospitalLevel&&record.hospitalGrade){
          return record.hospitalLevel+record.hospitalGrade
        }
        return 
      }
    },
    {
      title: '厂家',
      dataIndex: 'manufacturer',
      valueType:'select',
      valueEnum:manufacturerOption(),
      width:80
    },
    {
      title: '产品名称',
      ellipsis:true,
      dataIndex: 'product_name',
      width:120,
    },
    {
      title: '产品型号',
      dataIndex: 'product_standard',
      width:150,
      ellipsis:true,
    },
    {
      width:60,
      ellipsis:true,
      title: '单位',
      dataIndex: 'packing_unit',
      hideInSearch:true,
    },
    {
      width:120,
      title: '批号',
      dataIndex: 'batch',
    },
    // {
    //   width:100,
    //   title: '出库数量',
    //   dataIndex: 'numbs',
    //   hideInSearch:true,
    // },
    {
      width:100,
      title: '开票数量',
      dataIndex: 'numbs',
      hideInSearch:true,
      // renderText:(_,record)=>{
      //   if(record.bill_number){
      //     return  record.invoicedQuantity;
      //   }else{
      //     return  record.invoicing;
      //   }
      // },
    },
    {
      width:100,
      title: '单价(不含税)',
      dataIndex: 'invoicePrice',
      valueType: 'money',
      hideInSearch:true,
      renderText:(_,record)=>{
        if(record.invoicePrice){
          return  record.invoicePrice
        }
        if(record.standard_price){
          return  record.standard_price
        }
        return undefined;
      },
    },
    {
      width:120,
      title: '总价(不含税)',
      valueType: 'money',
      dataIndex: 'invoicePrice',
      renderText:(_,record)=>{
        if(record.invoicePrice&&record.numbs){
          return  record.invoicePrice*record.numbs;
        }
        if(record.standard_price&&record.numbs){
          return  record.standard_price*record.numbs;
        }
        return undefined;
      },
      hideInSearch:true
    },
    {
      width:100,
      title: '科室',
      dataIndex: 'hospitalDeptName',
      hideInSearch:true
    },
    {
      width:100,
      title: '销售',
      dataIndex: 'name',
      hideInSearch:true
    },
    {
      width:100,
      title: '一线管理',
      dataIndex: 'frontline',
      hideInTable:props.admin?false:true,
      hideInSearch:true,
    },
    {
      width:100,
      title: '二线管理',
      dataIndex: 'second',
      hideInTable:props.admin?false:true,
      hideInSearch:true,
    },
    // {
    //   title: '销售主要联系人',
    //   width: 120,
    //   dataIndex: 'liable',
    //   ellipsis:true,
    //   hideInSearch:true,
    // },
    {
      width:100,
      title: '采购单价(元)',
      dataIndex: 'buyPrice',
      valueType: 'money',
      hideInTable:props.admin?false:true,
      hideInSearch:true
    },
    {
      width:100,
      title: '采购总价(元)',
      valueType: 'money',
      dataIndex: 'buyPrice',
      hideInTable:props.admin?false:true,
      renderText:(_,record)=>{
        if(record.buyPrice){
          return  record.buyPrice*record.numbs;
        }
        return 0
        // if(record.bill_number){
        //   if(record.buyPrice){
        //     return  record.buyPrice*record.invoicedQuantity;
        //   }
        //   return  ''
        // }else{
        //   if(record.buyPrice){
        //     return  record.buyPrice*record.invoicing;
        //   }
        //   return ''
        // }
      },
      hideInSearch:true
    },
    {
      title: '医院级别',
      width: 80,
      dataIndex: 'hospitalLevel',
      hideInSearch:props.hospital===1?false:true,
      hideInTable:true,
    },
    {
      title: '医院评等',
      width: 80,
      hideInSearch:props.hospital===1?false:true,
      dataIndex: 'hospitalGrade',
      hideInTable:true,
    },
    // {
    //   title: '计入销量月份',
    //   width: 150,
    //   dataIndex: 'remarks',
    //   ellipsis:true,
    //   hideInSearch:true,
    // }, 
    {
      title: '操作',
      width: 200,
      ellipsis:true,
      render: (text, record, _, action) => {
        if(record.bill_number){
            if(sessionStorage.getItem('isShowAttach')!=='0'){
            return  <a
            key='file'
            onClick={async() => {
              var param:any={shipId:record.shipId};
              var fileData =  request('/xwyl/attachment/attachListData',{
                method: 'POST',
                requestType:'form',
                data: {
                  ...param,
                },
              });
              var val =await fileData;
              if(val.errorCode=200){
                val.data.forEach((element:any) => {
                  element.uid=element.id;
                  element.name=element.attName;
                  element.url=element.attPath;
                  element.status='done';
                });
                setTicketAttList(val.data);
                setShowDetail(true);
              }
            }}
          >
            附件
          </a>}else{
            return <></>
          }
        }else{
          return  notOpen(record)
        }
      }
    }
  ];

  return (
    <PageContainer>
    <ProTable
      scroll={props.admin?{x:3500}:{x:2900}}
      headerTitle={'报量统计'}
      actionRef={actionRef}
      request={(params, sorter, filter) => {
        if(params.date){
          params.beginDate=params.date[0];
          params.endDate=params.date[1];
          params.date=undefined;
        }
        if(props.admin){
            params.category = props.hospital==1?'1':'2';
            params.hospital = props.hospital
            // if(props.sale){
            //   params.isUpdate = "0"
            // }
        }else{
          // params.isUpdate = "0"
        }

        // if(props.hospital!==1){
        //   return invoicingFormLists({...params,filter})
        // }else{
        //   return invoicingFormList({...params,filter})
        // }
        return getVolumeStatistics({...params,filter})
       }}
      columns={columns}
      rowKey={record => record.id+record.put_out_no + record.product_standard+record.batch}
      search={{
        span: 7,
        labelWidth:100,
        defaultCollapsed: false,
        collapseRender:false,
        optionRender: ({ searchText, resetText }, { form }) => [
          <Button
            key='search'
            type='primary'
            onClick={() => {
              form?.submit();
            }}
          >
            {searchText}
          </Button>,
          <Button
            key='rest'
            onClick={() => {
              form?.resetFields();
              form?.submit();
            }}
          >
            {resetText}
          </Button>,
          <Button key='out' onClick={async()=>{
            setSpinningFlag(true);
            var date = form?.getFieldValue('date');
            var params:any={};
            if(date){
              params.beginDate=date[0].format('YYYY-MM-DD');
              params.endDate=date[1].format('YYYY-MM-DD');
              params.date=undefined;
            }
            params.loginName=form?.getFieldValue('loginName');
            params.cnName= form?.getFieldValue('cnName');
            params.bill_number= form?.getFieldValue('bill_number');
            params.bh= form?.getFieldValue('bh');
            params.purchaser= form?.getFieldValue('purchaser');
            params.put_out_no= form?.getFieldValue('put_out_no');
            params.manufacturer= form?.getFieldValue('manufacturer');
            params.product_name= form?.getFieldValue('product_name');
            params.product_standard= form?.getFieldValue('product_standard');
            params.batch= form?.getFieldValue('batch');
            params.hospital = props.hospital
            params.hospitalLevel = form?.getFieldValue('hospitalLevel');
            params.hospitalGrade= form?.getFieldValue('hospitalGrade');
            params.level= form?.getFieldValue('level');
            params.invoicing = form?.getFieldValue('invoicing');
            if(props.admin){
              params.category = props.hospital==1?'1':'2';
            }
            params.volumeType = form?.getFieldValue('volumeType');
            params.isUpdate = form?.getFieldValue('isUpdate');
            if(props.admin){
              // if(props.sale){
              //   params.isUpdate = "0"
              // }
            }else{
              // params.isUpdate = "0"
            }
            var val = undefined;
            params.export=true
            val = await getVolumeStatistics(params);
            if(val.errorCode==='200'){
              exportFile(val.data,props.hospital==1?'医院销量.xlsx':'客户销量.xlsx')
            }else{
              message.error(val.errorMessage);
            }
            setSpinningFlag(false);
          }}>导出</Button>,
        ],
      }}
      toolBarRender={false}
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      toolbar={{settings:[]}}
      />
      <Drawer
            width={1000}
            title='详情'
            visible={showDetail}
            onClose={()=>setShowDetail(false)}
            destroyOnClose={true}>
               <Upload   fileList={ticketAttList}  onPreview={handlePreview} showUploadList={{showRemoveIcon:false}}>
              </Upload>
      </Drawer>
      <Spin spinning={spinningFlag} style={{transform:'translate(-50%,-50%)',left:'50%',top:'50%',position:'absolute'}}/>

  </PageContainer>
  );
}

export default HadTicket;